// Package database @program: account
//@author: edte
//@create: 2021-12-28 14:07
package database

import (
	log2 "account/log"
	"account/tools"
	"context"
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func AdminLogin(username string, password string) (tools.AdminUser, error) {
	mysqlPath := tools.GetEnv("MYSQL_PATH", "localhost:3306")
	mysqlUser := tools.GetEnv("MYSQL_USER", "root")
	mysqlPassword := tools.GetEnv("MYSQL_PASSWORD", "123456")
	db, err := gorm.Open(mysql.Open(mysqlUser+":"+mysqlPassword+"@tcp("+mysqlPath+")/admins?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "account", "AdminLogin", username, "Error", "failed to connect database")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}

		return tools.AdminUser{}, errors.New("failed to connect database")
	}
	err = db.AutoMigrate(&tools.AdminUser{})
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "account", "AdminLogin", username, "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return tools.AdminUser{}, err
	}
	// db, err := gorm.Open(mysql.Open("root:123456@tcp(localhost:3306)/admins?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})
	tmpUser := tools.AdminUser{}
	db.Model(&tools.AdminUser{}).Where("admin_num = ?", username).First(&tmpUser)
	if tmpUser.Id == 0 {
		writeLog, err2 := log2.WriteLog(context.Background(), "account", "AdminLogin", username, "Warring", "Account does not exist.")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return tools.AdminUser{}, errors.New("account does not exist")
	}
	if tmpUser.AdminPD != password || tmpUser.AdminNum != username {
		writeLog, err2 := log2.WriteLog(context.Background(), "account", "AdminLogin", username, "Warring", "Incorrect account or password")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return tools.AdminUser{}, errors.New("incorrect account or password")
	}

	return tmpUser, err

}
